/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.gt.web;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.gt.entity.GtTrain;
import com.thinkgem.jeesite.modules.gt.entity.GtTrainPeople;
import com.thinkgem.jeesite.modules.gt.service.GtTrainPeopleService;
import com.thinkgem.jeesite.modules.gt.service.GtTrainService;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 技术培训信息Controller
 * @author zad
 * @version 2018-03-26
 */
@Controller
@RequestMapping(value = "${frontPath}/gt/gtTrain")
public class GtTrainController extends BaseController {

	@Autowired
	private GtTrainService gtTrainService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private GtTrainPeopleService gtTrainPeopleService;
	
	@ModelAttribute
	public GtTrain get(@RequestParam(required=false) String id) {
		GtTrain entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = gtTrainService.get(id);
		}
		if (entity == null){
			entity = new GtTrain();
		}
		return entity;
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(GtTrain gtTrain,String menuId, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		this.areaService.fetchRegions(model);
		if(null == gtTrain.getArea() || StringUtils.isBlank(gtTrain.getArea().getCode()))
		{
			Area area = UserUtils.getUser().getArea();
			gtTrain.setArea(area);
		}
		
		Page<GtTrain> page = gtTrainService.findPage(new Page<GtTrain>(request, response), gtTrain); 
		model.addAttribute("page", page);
		
		model.addAttribute("gtTrain", gtTrain);
		model.addAttribute("menuId", menuId);
		
		return "modules/gt/basic/gtTrainList";
	}
	
	/**
     * 导出文件
     */
    @RequestMapping("downLoad")
    public void downLoad(String areaId,GtTrainPeople gtTrainPeople,String timeStamp, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException{
    	
    	Area area = null;
    	if("undefined".equals(areaId))
    	{
    		areaId = "";
    	}
    	if(!StringUtils.isEmpty(areaId))
		{
			area = this.areaService.get(areaId);
		}
    	    	
    	response.setCharacterEncoding("utf-8");
    	String fileName = UserUtils.getUser().getArea().getName() + Global.getConfig("exportTrainFileName");
    	
    	if(null != area)
    	{
    		fileName = area.getName() + Global.getConfig("exportTrainFileName");
    	}
    	
    	
    	fileName += DateUtils.getDate();
        // fileName = URLEncoder.encode(fileName, "UTF-8");
    	
    	// response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        
        SXSSFWorkbook wb = new SXSSFWorkbook(-1);
        // turn off auto-flushing and accumulate all rows in memory  
        wb.setCompressTempFiles(true); //使用gzip压缩,减小空间占用  
        Sheet sh = wb.createSheet("技术培训扶贫信息");
        OutputStream out = new BufferedOutputStream(response.getOutputStream());
        try { //从数据库中得到结果  
        	
        	
        	
        	GtTrain gtTrain = new GtTrain();
        	if(null == gtTrain.getArea() || StringUtils.isBlank(gtTrain.getArea().getCode()))
    		{
        		if(StringUtils.isEmpty(areaId))
        		{
	    			area = UserUtils.getUser().getArea();
	    			gtTrain.setArea(area);
        		}
        		else
        		{
        			gtTrain.setArea(area);
        		}
    		}
        	gtTrainPeople.setTrain(gtTrain);
        	
        	Page<GtTrainPeople> page = new Page<GtTrainPeople>();
        	page.setOrderBy("b.update_date,b.id,a.update_date");
        	gtTrainPeople.setPage(page);
        	
        	
        	
            List<GtTrainPeople> list = this.gtTrainPeopleService.findList(gtTrainPeople);
            
            if(null == list || list.size() < 1)
            {
	            sh.setColumnWidth(0, 50 * 256);
	        	Row rowHeader = sh.createRow(0);
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("信息提示");
	            
	            Row row = sh.createRow(1);
	            Cell cell = row.createCell(0);  
	            cell.setCellValue("没有找到相关条件的数据。");  
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
            }else
            {
	            
	            //设置每一列的宽度,注意 要乘以256,因为1代表excel中一个字符的1/256的宽度  
	            sh.setColumnWidth(0, 5 * 256);
	            sh.setColumnWidth(1, 10 * 256);
	            sh.setColumnWidth(2, 40 * 256);
	            sh.setColumnWidth(3, 12 * 256);
	            sh.setColumnWidth(4, 10 * 256);
	            sh.setColumnWidth(5, 15 * 256);
	            
	            sh.setColumnWidth(6, 9 * 256);
	            sh.setColumnWidth(7, 25 * 256);
	            sh.setColumnWidth(8, 20 * 256);
	            sh.setColumnWidth(9, 30 * 256);
	           /* sh.setColumnWidth(10, 10 * 256);
	            sh.setColumnWidth(11, 10 * 256);*/
	            Row rowHeader = sh.createRow(0);
	            /*CellStyle headerStyle = rowHeader.getRowStyle();
	            headerStyle.setAlignment(CellStyle.ALIGN_CENTER);*/
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("序号");
	            cellHeader = rowHeader.createCell(1);
	            cellHeader.setCellValue("培训单位");
	            cellHeader = rowHeader.createCell(2);
	            cellHeader.setCellValue("培训内容");
	            cellHeader = rowHeader.createCell(3);
	            cellHeader.setCellValue("重点村总数");
	            cellHeader = rowHeader.createCell(4);
	            cellHeader.setCellValue("联系人");
	            cellHeader = rowHeader.createCell(5);
	            cellHeader.setCellValue("联系方式");
	            
	            cellHeader = rowHeader.createCell(6);
	            cellHeader.setCellValue("姓名");
	            cellHeader = rowHeader.createCell(7);
	            cellHeader.setCellValue("家庭住址");
	            cellHeader = rowHeader.createCell(8);
	            cellHeader.setCellValue("身份证号");
	            cellHeader = rowHeader.createCell(9);
	            cellHeader.setCellValue("方式");
	            /*cellHeader = rowHeader.createCell(10);
	            cellHeader.setCellValue("金额");
	            cellHeader = rowHeader.createCell(11);
	            cellHeader.setCellValue("备注");*/
	            
	            // 只取5000条数据
	            /*if(null != list && list.size() > Constant.Join.JOIN_EXPORT_MOST_ROWS)
	            {
	            	list.subList(Constant.Join.JOIN_EXPORT_MOST_ROWS, list.size()).clear();
	            }*/
	            
	            // 记录本次技术培训信息id，用于区分是不是同一个技术培训信息
	            String nowTrainId = null;
	            // 本次技术培训信息合并单元格开始行数，默认为0；
	            int nowTrainBeginRow = 0;
	            // 序号
	            int seq = 1;
	            int size = list.size();
	            for(int i = 0; i < size; i++) {
	            	
	            	// 当前技术培训
	            	GtTrainPeople trainPeople = list.get(i);
	            	
	            	// 下一个技术培训
	            	GtTrainPeople trainPeopleNext = null;
	            	// 存在下一个，则获取下一个，用于查看本次技术培训与下一个技术培训是否是同一个技术培训
	            	if(i+1 < size)
	            	{
	            		trainPeopleNext = list.get(i+1);
	            	}
	            	else
	            	{
	            		trainPeopleNext = null;
	            	}
	            	
	            	Row row = sh.createRow(i+1);
	                Cell cell = row.createCell(0);  
	            	
	            	// 第一次初始化本次技术培训id
	            	if(i == 0)
	            	{
	            		nowTrainId = trainPeople.getTrain().getId();
	            		nowTrainBeginRow = 0;
	            		cell.setCellValue(seq);
		                cell = row.createCell(1);
		                cell.setCellValue(trainPeople.getTrain().getArea().getName());
		                cell = row.createCell(2);
		                cell.setCellValue(trainPeople.getTrain().getContent());  
		                cell = row.createCell(3);
		                cell.setCellValue(null == trainPeople.getTrain().getArea().getCountryTotal() ? "":String.valueOf(trainPeople.getTrain().getArea().getCountryTotal()));
		                cell = row.createCell(4);
		                cell.setCellValue(trainPeople.getTrain().getCreateBy().getOperName());
		                cell = row.createCell(5);
		                cell.setCellValue(trainPeople.getTrain().getCreateBy().getMobile());
	            	}
	            	// 判断
	            	else
	            	{
	            		// 上一个技术培训信息id
	            		String lastTrainId = list.get(i-1).getTrain().getId();
	            		// 本次技术培训信息id和上次技术培训信息id不一致，则说明本次是新的技术培训开始
	            		if(!lastTrainId.equals(trainPeople.getTrain().getId()))
	            		{
	            			nowTrainBeginRow = i;
	            			seq ++;
	            			
	            			cell.setCellValue(seq);
	    	                cell = row.createCell(1);
	    	                cell.setCellValue(trainPeople.getTrain().getArea().getName());
	    	                cell = row.createCell(2);
	    	                cell.setCellValue(trainPeople.getTrain().getContent());  
	    	                cell = row.createCell(3);
	    	                cell.setCellValue(null == trainPeople.getTrain().getArea().getCountryTotal() ? "":String.valueOf(trainPeople.getTrain().getArea().getCountryTotal()));
	    	                cell = row.createCell(4);
	    	                cell.setCellValue(trainPeople.getTrain().getCreateBy().getOperName());
	    	                cell = row.createCell(5);
	    	                cell.setCellValue(trainPeople.getTrain().getCreateBy().getMobile());
	            		}
	            		
	            	}
	            	
	            	
	                /*Row row = sh.createRow(i+1);
	                Cell cell = row.createCell(0);  
	                cell.setCellValue(seq);
	                cell = row.createCell(1);
	                cell.setCellValue(trainPeople.getTrain().getArea().getName());
	                cell = row.createCell(2);
	                cell.setCellValue(trainPeople.getTrain().getContent());  
	                cell = row.createCell(3);
	                cell.setCellValue(null == trainPeople.getTrain().getArea().getCountryTotal() ? "":String.valueOf(trainPeople.getTrain().getArea().getCountryTotal()));
	                cell = row.createCell(4);
	                cell.setCellValue(trainPeople.getTrain().getCreateBy().getOperName());
	                cell = row.createCell(5);
	                cell.setCellValue(trainPeople.getTrain().getCreateBy().getMobile());*/
	                
	                cell = row.createCell(6);
	                cell.setCellValue(trainPeople.getName());
	                cell = row.createCell(7);
	                cell.setCellValue(trainPeople.getAddress());
	                cell = row.createCell(8);
	                cell.setCellValue(trainPeople.getIdcard());
	                cell = row.createCell(9);
	                /*cell.setCellValue(DictUtils.getDictLabel(trainPeople.getHelpType(), "gt_help_type", null) 
	                		+ ("o".equals(trainPeople.getHelpType())?"(" + trainPeople.getHelpOther() + ")":""));*/
	                
	                String helpType = trainPeople.getHelpType();
	                if(StringUtils.isEmpty(helpType))
	                {
	                	cell.setCellValue("");
	                }else
	                if(helpType.length() < 2){
	                	cell.setCellValue(DictUtils.getDictLabel(helpType, "gt_help_type", null) 
	                		+ ("o".equals(helpType)?"(" + trainPeople.getHelpOther() + ")":""));
	                }
	                else
	                {
	                	String helpVal = "";
	                	String [] helpArr = helpType.split(",");
	                	for(String help:helpArr)
	                	{
	                		if(StringUtils.isEmpty(help))
	                		{
	                			continue;
	                		}
	                		
	                		helpVal += DictUtils.getDictLabel(help, "gt_help_type", null) + " ";
	                		if("o".equals(help))
	                		{
	                			helpVal += "(" + trainPeople.getHelpOther() + ")";
	                		}
	                	}
	                	cell.setCellValue(helpVal);
	                	
	                }
	                
	                /*cell = row.createCell(10);  
	                cell.setCellValue(null == trainPeople.getMoney()?"0":String.valueOf(trainPeople.getMoney()));
	                cell = row.createCell(11);  
	                cell.setCellValue(trainPeople.getRemarks());*/
	                
	                
	                // 对比本次技术培训和下一个技术培训是否是同一个，
	            	if(i > 0)
	            	{
	            		nowTrainId = trainPeople.getTrain().getId();
	            		// 没有下一个技术培训信息或者下一个技术培训信息和本次技术培训信息不是同一个，则开始合并单元格
	            		if(null == trainPeopleNext || !nowTrainId.equals(trainPeopleNext.getTrain().getId()))
	            		{
	            			for(int col = 0; col < 6; col ++)
	            			{
		            			// 合并单元格，开始行为 nowTrainBeginRow + 1，结束行为i + 1(+1是因为第0行为标题)
		            			CellRangeAddress cellAddr = new CellRangeAddress(nowTrainBeginRow + 1, i + 1, col, col);
		            			sh.addMergedRegion(cellAddr);
	            			}
	            		}
	            	}
	                
	      
	                /*if(i > 0 && (i % 1000 == 0)) {  
	                    ((SXSSFSheet) sh).flushRows();  
	                } */
	            }
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
	            
            }
        } catch(Exception e) {
        	sh.setColumnWidth(0, 50 * 256);
        	Row rowHeader = sh.createRow(0);
            Cell cellHeader = rowHeader.createCell(0);
            cellHeader.setCellValue("信息提示");
            
            Row row = sh.createRow(1);
            Cell cell = row.createCell(0);  
            cell.setCellValue("导出失败，请联系管理员。错误信息：" + e.getMessage());  
            
            e.printStackTrace();
            ((SXSSFSheet) sh).flushRows();
            
            CookieUtils.rememberCookieToken(timeStamp,request,response);
            //统一写出方法
            FileUtils.writeWb(wb,out);
        }  
     // 保存日志
     request.setAttribute("title", "用户" + UserUtils.getUser().getLoginName() + "导出了文件：" + fileName);
    }

	// 技术培训扶贫人列表
	@RequestMapping(value = {"listTrainPeople"})
	public String listTrainPeople(GtTrainPeople gtTrainPeople, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		
		Page<GtTrainPeople> page = gtTrainPeopleService.findPage(new Page<GtTrainPeople>(request, response), gtTrainPeople); 
		model.addAttribute("page", page);
		gtTrainPeople.setTrain(this.gtTrainService.get(gtTrainPeople.getTrain().getId()));
		model.addAttribute("gtTrainPeople", gtTrainPeople);
		
		return "modules/gt/basic/gtTrainPeopleList";
	}
		
		
	@RequestMapping(value = "form")
	public String form(GtTrain gtTrain, Model model) {
		
		this.areaService.fetchRegions(model);
		
		model.addAttribute("gtTrain", gtTrain);
		return "modules/gt/basic/gtTrainForm";
	}

	
	@RequestMapping(value = "formTrainPeople")
	public String formTrainPeople(GtTrainPeople gtTrainPeople, Model model) {
		
		gtTrainPeople.setTrain(this.gtTrainService.get(gtTrainPeople.getTrain().getId()));
		
		List<Dict> helpTypes = DictUtils.getDictList("gt_help_type");
		model.addAttribute("helpTypes", helpTypes);
		
		// 修改时，查询相关信息
		if(StringUtils.isNotBlank(gtTrainPeople.getId()))
		{ 
			// 记住菜单id
			String menuId = gtTrainPeople.getMenuId();
			gtTrainPeople = this.gtTrainPeopleService.get(gtTrainPeople.getId());
			gtTrainPeople.setMenuId(menuId);
		}
		
		model.addAttribute("gtTrainPeople", gtTrainPeople);
		return "modules/gt/basic/gtTrainPeopleForm";
	}

	
	@RequestMapping(value = "save")
	public String save(GtTrain gtTrain, Model model,String oper,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, gtTrain)){
			return form(gtTrain, model);
		}
		

		
		if(StringUtils.isBlank(gtTrain.getId()))
		{
			// 日志标题
			request.setAttribute("title", "添加技术培训:" + gtTrain.getName());
		}else
		{
			// 日志标题
			request.setAttribute("title", "修改技术培训:" + gtTrain.getName());
		}
		
		
		
		Map<String,String> fileRs = FileUtils.writeFile(request, "file1", "train");
		if(null != fileRs)
		{
			gtTrain.setFileName1(fileRs.get("fileName"));
			gtTrain.setFilePath1(fileRs.get("filePath"));
		}
		fileRs = FileUtils.writeFile(request, "file2", "train");
		if(null != fileRs)
		{
			gtTrain.setFileName2(fileRs.get("fileName"));
			gtTrain.setFilePath2(fileRs.get("filePath"));
		}
		
		gtTrainService.save(gtTrain);
		addMessage(redirectAttributes, "保存技术培训信息成功");
		
		if("form".equals(oper))
		{
			return "redirect:"+super.frontPath+"/gt/gtTrain/form?menuId=" + gtTrain.getMenuId();
		}
		
		return "redirect:"+super.frontPath+"/gt/gtTrain?menuId=" + gtTrain.getMenuId();
	}
	
	@RequestMapping(value = "saveTrainPeople")
	public String saveTrainPeople(GtTrainPeople gtTrainPeople, HttpServletRequest request, HttpServletResponse response,String oper, Model model, RedirectAttributes redirectAttributes) {
		

		
		if(StringUtils.isBlank(gtTrainPeople.getId()))
		{
			// 日志标题
			request.setAttribute("title", "添加技术培训贫困人:" + gtTrainPeople.getName());
		}else
		{
			// 日志标题
			request.setAttribute("title", "修改技术培训贫困人:" + gtTrainPeople.getName());
		}
		
		
		
		gtTrainPeopleService.save(gtTrainPeople);
		addMessage(redirectAttributes, "保存技术培训贫困人口信息成功");
		
		// model.addAttribute("gtTrainPeople", gtTrainPeople);
		// redirectAttributes.addFlashAttribute("gtTrainPeople", gtTrainPeople);
		
		// 保存后继续到添加页面
		if("form".equals(oper))
		{
			return "redirect:"+super.frontPath+"/gt/gtTrain/formTrainPeople/?train.id=" + gtTrainPeople.getTrain().getId() + "&menuId=" + gtTrainPeople.getMenuId();
		}
		else
		{
			return "redirect:"+super.frontPath+"/gt/gtTrain/listTrainPeople/?train.id=" + gtTrainPeople.getTrain().getId() + "&menuId=" + gtTrainPeople.getMenuId();
		}
	}
	
	@RequestMapping(value = "delete")
	public String delete(GtTrain gtTrain,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		
		this.gtTrainPeopleService.deleteByTrainId(gtTrain.getId());
		gtTrainService.delete(gtTrain);
		
		addMessage(redirectAttributes, "删除技术培训信息成功");
		
		
		// 日志标题
		request.setAttribute("title", "删除技术培训(及其下扶贫人):" + gtTrain.getId());
		
		
		return "redirect:"+super.frontPath+"/gt/gtTrain?menuId=" + gtTrain.getMenuId();
	}
	
	@RequestMapping(value = "deleteTrainPeople")
	public String deleteTrainPeople(GtTrainPeople gtTrainPeople,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		
		this.gtTrainPeopleService.delete(gtTrainPeople);
		addMessage(redirectAttributes, "删除技术培训贫困人口信息成功");
		
		
		// 日志标题
		request.setAttribute("title", "删除技术培训贫困人:" + gtTrainPeople.getId());
		
		
		return "redirect:"+super.frontPath+"/gt/gtTrain/listTrainPeople?train.id=" + gtTrainPeople.getTrain().getId() + "&menuId=" + gtTrainPeople.getMenuId();
	}

}